package com.example.springbootredisdemo.config;

import com.example.springbootredisdemo.listener.Listener1;
import com.example.springbootredisdemo.listener.Listener2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * @author sharloon
 * @date 2023/6/26
 */
@Configuration
public class RedisConfig {

    public static final String TOPIC = "topic_1";

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter,
                                            MessageListenerAdapter listenerAdapter2) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, new PatternTopic(TOPIC));
        container.addMessageListener(listenerAdapter2, new PatternTopic(TOPIC));
        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(Listener1 listener1) {
        System.out.println("listener1 register");
        MessageListenerAdapter listenerAdapter = new MessageListenerAdapter(listener1, "onMessage");
        listenerAdapter.setSerializer(RedisSerializer.json());
        return listenerAdapter;
    }

    @Bean
    MessageListenerAdapter listenerAdapter2(Listener2 listener2) {
        System.out.println("listener2 register");
        MessageListenerAdapter listenerAdapter = new MessageListenerAdapter(listener2, "onMessage");
        listenerAdapter.setSerializer(RedisSerializer.java());
        return listenerAdapter;
    }
}
